package com.taotao.sso.service;


import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.common.service.RedisService;
import com.taotao.sso.mapper.UserMapper;
import com.taotao.sso.pojo.User;

@Service
public class UserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private RedisService redisService;
	
	private static final ObjectMapper MAPPER = new ObjectMapper();
	public Boolean check(String param, Integer type) {
		User user = new User();
		switch (type) {
		case 1:
			user.setUsername(param);
			break;
		case 2:
			user.setPhone(param);
			break;
		case 3:
			user.setEmail(param);
			break;

		default:
			break;
		}
		return this.userMapper.selectOne(user)==null;
	}

	public Boolean saveUser(User user) {
		// TODO Auto-generated method stub
		user.setId(null);
		user.setCreated(new Date());
		user.setUpdated(user.getCreated());
		//密码加密MD5
		user.setPassword(DigestUtils.md5Hex(user.getPassword()));
		return this.userMapper.insert(user)==1;
	}

	public String doLogin(String username, String password) throws Exception {
		User record = new User();
		record.setUsername(username);
		User user = this.userMapper.selectOne(record);
		//对比用户名是否为空
		if (null==user) {
			return null;
		}
		//对比密码是否一致
		if (!StringUtils.equals(DigestUtils.md5Hex(password), user.getPassword())) {
			return null;
		}
		String token = DigestUtils.md5Hex(System.currentTimeMillis()+username);
		//登录成功的用户数据放到redis缓存中
		this.redisService.set("TOKEN_"+token , MAPPER.writeValueAsString(user), 60*30);
		return token;
	}
	
	public User getCookie(String token){
		String key = "TOKEN_"+token;
		String string = redisService.get(key);
		try {
			redisService.expire(string, 1800);
			User user = MAPPER.readValue(string, User.class);
			return user;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
